<?php

namespace app\admin\controller\ykjp\purchase;

use app\common\controller\Backend;
use think\Db;

/**
 * 退货管理
 *
 * @icon fa fa-circle-o
 */
class Retire extends Backend {

    /**
     * Retire模型对象
     * @var \app\admin\model\ykjp\purchase\Retire
     */
    protected $model = null;
    protected $distinguish = true;
    protected $wherename = "";

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\purchase\Retire;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $this->wherename = "retire.firmid";
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {

                $row->getRelation('supplier')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {
        if ($this->request->isAjax()) {
            $row = $this->request->param("row/a");
            $product = $this->request->param("product/a");

            if (!$row) {
                $this->error(__("Please add basic information such as suppliers"));
            }
            if (!$product) {
                $this->error("Please add product");
            }

            $all = json_decode($product[0]);
            $tep = $this->model->object_array($all);
            if (!$tep) {
                $this->error("Please add product");
            }

            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $firmid = $this->auth->firmid;
            $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
            $row['billing_time'] = strtotime($row['billing_time']);
            $row['createtime'] = time();
            $row['updatetime'] = time();
            $row['firmid'] = $this->auth->firmid;
            $row['admin_id'] = $this->auth->id;
            $row['status'] = "0";
            $insertId = $this->model->insertGetId($row);
            $arr = [];
            if ($insertId) {
                foreach ($tep as $key => $val) {
                    $val['retire_id'] = $insertId;
                    $val['warehouse_id'] = $row['warehouse_id'];
                    $val['createtime'] = time();
                    $val['updatetime'] = time();
                    $val['status'] = "0";
                    $val['firmid'] = $this->auth->firmid;
                    $arr[] = $val;
                }
                $insert = $resProModel->insertAll($arr);
                if ($insert) {
                    $this->success(null, null, array("result" => "success", "url" => url("/ykjp/purchase/retire/index")));
                } else {
                    $this->model->where("id", $insertId)->delete();
                }
            }
            $this->error(__('Operation fail'));
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = null) {
        if ($ids) {
            if ($this->request->isAjax()) {
                $deltial = $this->model->where("id", "in", $ids)->where("firmid", $this->auth->firmid)->field("id")->select();
                $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
                if ($deltial) {
                    $count = 0;
                    foreach ($deltial as $key => $val) {
                        $data = array('deletetime' => time());
                        $del = $this->model->where("firmid", $this->auth->firmid)->where("id", $val['id'])->update($data);
                        $count += $del;
                        if ($del) {
                            $resProModel->where("firmid", $this->auth->firmid)->where("retire_id", $val['id'])->update($data);
                        }
                    }
                    if ($count) {
                        $this->success();
                    }
                    $this->error(__('Operation fail'));
                }
            }
            $this->error(__('Illegal operation'));
        }

        $this->error(__('Parameter %s can not be empty', "ids"));
    }

    /**
     * 详情
     */
    public function detail($ids) {
        if ($ids) {
            $detail = $this->model->with(['supplier'])->where("retire.id", $ids)->where("retire.firmid", $this->auth->firmid)->select();
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $product = [];
            if ($detail) {
                $product = $resProModel->with(['products'])->where("retprodcut.firmid", $this->auth->firmid)->where("retire_id", $ids)->select();
                foreach ($product as $key => $val) {
                    $pro = json_decode($val['products']['prop']);
                    $val['products']['prop'] = $this->model->object_array($pro);
                }
            }
            $this->assign("detail", $detail);
            $this->assign("product", $product);
            return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/index");
    }

    /**
     * 反审核
     */
    public function Anti($ids) {
        if ($ids) {
            $all = $this->model->where("id", "in", $ids)->where("firmid", $this->auth->firmid)->select();
            $time = time();
            $data = array("status" => "0", "updatetime" => $time, "reason" => null);
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $count = 0;
            foreach ($all as $key => $val) {
                $up = $this->model->where("id", $val['id'])->update($data);
                $count += $up;
                if ($up) {
                    $data = array("status" => "0", "updatetime" => $time);
                    $resProModel->where("firmid", $this->auth->firmid)->where("retire_id", $val['id'])->update($data);
                }
            }
            if ($count) {
                $this->success();
            }
            $this->error(__('Operation fail'));
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/detail");
    }

    /**
     * 编辑
     */
    public function edit($ids = "") {
        if ($ids) {
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;

            $select = $this->model->where("id", $ids)->where("firmid", $this->auth->firmid)->find();
            if (!$select) {
                $this->error(__("Please add basic information such as suppliers", "ykjp/purchase/retire/index"));
            }
            if ($select['status'] != "0") {
                $this->error(__("Not editable", "ykjp/purchase/retire/detail"));
            }
            if ($this->request->isAjax()) {
                $row = $this->request->param("row/a");
                $product = $this->request->param("product/a");

                if (!$row) {
                    $this->error(__("Please add basic information such as suppliers"));
                }
                if (!$product) {
                    $this->error("Please add product");
                }
                $select = $this->model->where("id", $ids)->where("firmid", $this->auth->firmid)->find();
                if (!$select) {
                    $this->error(__("Please add basic information such as suppliers"));
                }
                if ($select['status'] != "0") {
                    $this->error(__("Not editable"));
                }
                $all = json_decode($product[0]);
                $tep = $this->model->object_array($all);
                if (!$tep) {
                    $this->error("Please add product");
                }
                $row['status'] = "0";
                $updatetime = time();
                $row['billing_time'] = strtotime($row['billing_time']);
                $row['updatetime'] = $updatetime;
                $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
                $up = $this->model->where("id", $ids)->update($row);
                if ($up) {
                    $where = [];
                    $count = 0;
                    foreach ($tep as $key => $val) {
                        $data_id = $val['data_id'];
                        unset($val['data_id']);
                        $val['warehouse_id'] = $row['warehouse_id'];
                        //先查询是否存在
                        if ($data_id != "") {
                            $val['updatetime'] = $updatetime;
                            $updateWhere = array(
                                "firmid" => $this->auth->firmid,
                                "id" => $data_id,
                                "retire_id" => $ids
                            );
                            $update = $resProModel->where($updateWhere)->update($val);
                            if ($update) {
                                $count += 1;
                                $where[] = $data_id;
                            }
                        } else {
                            $val['retire_id'] = $ids;
                            $val['warehouse_id'] = $row['warehouse_id'];
                            $val['createtime'] = $updatetime;
                            $val['updatetime'] = $updatetime;
                            $val['status'] = "0";
                            $val['firmid'] = $this->auth->firmid;
                            $ins = $resProModel->insertGetId($val);
                            if ($ins) {
                                $count += 1;
                                $where[] = $ins;
                            }
                        }
                    }
                    if ($where) {
                        $del = $resProModel->where("retire_id", $ids)->where("firmid", $this->auth->firmid)->where("id", "not in", $where)->update(array("deletetime" => time()));
                    }
                    if ($count) {
                        $this->success(null, null, array('result' => "success"));
                    }
                    $this->error(__('Operation fail'));
                }
            }
            $detail = $this->model->with(['supplier'])->where("retire.id", $ids)->where("retire.firmid", $this->auth->firmid)->select();
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            $product = [];
            if ($detail) {
                $product = $resProModel->with(['products'])->where("retprodcut.firmid", $this->auth->firmid)->where("retire_id", $ids)->select();
                if ($product) {
                    foreach ($product as $key => $val) {
                        $pro = json_decode($val['products']['prop']);
                        $val['products']['prop'] = $this->model->object_array($pro);
                    }
                }
            }
            $this->assign("detail", $detail);
            $this->assign("product", $product);
            return $this->view->fetch();
        }
        $this->error(__('Parameter %s can not be empty', "ids"), "ykjp/purchase/retire/detail");
    }

    /**
     * 确认退货
     */
    public function confirm($ids = "") {
        if ($ids) {
            $resProModel = new \app\admin\model\ykjp\purchase\Retprodcut;
            if ($this->request->isAjax()) {
                $type = $this->request->param("type");
                if (!$type) {
                    $this->error(__('Parameter %s can not be empty', "type"));
                }
                //验证查询提交的对象是否已经通过审核
                $all = $this->model->where("firmid", $this->auth->firmid)->where("status", "1")->where("id", "in", $ids)->select();
                if ($all) {
                    $count = 0;
                    if ($type == "yes") {
                        foreach ($all as $key => $val) {
                            $data = array("updatetime" => time(), "status" => "3");
                            $up = $this->model->where("id", $val['id'])->update($data);

                            if ($up) {

                                $upProduct = $resProModel->where("retire_id", $val['id'])->update($data);
                                $count += $upProduct;
                                if (!$upProduct) {
                                    $count -= 1;
                                    $this->model->where("id", $val['id'])->update(array('status' => "1"));
                                }
                                if ($count) {
                                    $this->success(null, null, array("result" => "success"));
                                }
                                $this->error(__('Operation fail'));
                            }
                        }
                    } else if ($type == "no") {
                        $txt = $this->request->param("why");
                        // var_dump($txt);exit;
                        $count = 0;
                        foreach ($all as $key => $val) {
                            $updatetime = time();
                            $data = array("updatetime" => $updatetime, "status" => "4", "why" => $txt);
                            $up = $this->model->where("id", $val['id'])->update($data);
                            if ($up) {
                                $update = $resProModel->where("retire_id", $val['id'])->update(array("updatetime" => time(), "status" => "4"));
                                $count += $update;
                                if (!$update) {
                                    $data = array("status" => "1", "why" => "");
                                    $count -= 1;
                                    $this->model->where("id", $val['id'])->update($data);
                                }
                            }
                        }
                        if ($count) {
                            $this->success(null, null, array("result" => "success"));
                        }
                        $this->error(__('Operation fail'));
                    }
                }
            }
            $this->error(__('Operation fail'));
        }
        $this->error(__('Parameter %s can not be empty', "ids"));
    }

}
